package com.miku.blog.domain.pojo;

import com.alibaba.fastjson.annotation.JSONField;
import com.miku.blog.domain.Role;
import com.miku.blog.domain.UserAuth;
import com.miku.blog.domain.UserInfo;
import com.miku.blog.domain.UserLoginInfo;
import com.miku.blog.domain.dto.ResourceUserDTO;
import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author shkstart
 * @create ${}YEAR-05-24 23:24
 */
@Data
@Accessors(chain = true)
public class LoginUser implements UserDetails {

    private String key;
    private UserInfo userInfo;
    private UserLoginInfo userLoginInfo;
    private UserAuth userAuth;
    private Role role;
    private Map<String, List<ResourceUserDTO>> resourceMap;

    //不序列化到redis中
    @JSONField(serialize = false)
    private List<GrantedAuthority> authorities;

    public LoginUser() {
        this.key = UUID.randomUUID().toString().replace("-","");
    }

    public LoginUser(UserAuth userAuth, Role role) {
        this();
        this.userAuth = userAuth;
        this.role = role;
    }

    public LoginUser(UserInfo userInfo, UserLoginInfo userLoginInfo, UserAuth userAuth, Role role) {
        this();
        this.userInfo = userInfo;
        this.userLoginInfo = userLoginInfo;
        this.userAuth = userAuth;
        this.role = role;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (Objects.isNull(this.authorities) && Objects.nonNull(this.role)) {
            this.authorities =
                    Collections.singletonList(new SimpleGrantedAuthority(role.getRoleLabel()));
        }
        return this.authorities;
    }

    @Override
    public String getPassword() {
        return userAuth.getPassword();
    }

    @Override
    public String getUsername() {
        return userAuth.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        if (Objects.nonNull(userInfo) && userInfo.getIsDisable().equals(SystemConstance.IS_DISABLE)){
            return false;
        }
        return true;
    }
}
